package com.winit.openapi.lma.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.lma.LMAShipmentPreAdviceService;
import com.winit.oms.spi.lma.command.CreateShipmentPreAdviceCommand;
import com.winit.oms.spi.lma.command.PrintManifestCommand;
import com.winit.oms.spi.lma.vo.LMAShipmentPreAdviceTaskVo;
import com.winit.oms.spi.lma.vo.LMAShipmentPreAdviceVo;
import com.winit.oms.spi.vo.CreatePreAdviceResult;
import com.winit.oms.spi.vo.v2.response.ErrorResult;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.WinitLabelParser;

@Controller
@RequestMapping(value = "/lma/manifest")
public class LMAShipmentManifestController extends BaseController {
    
	
    @Resource
    private LMAShipmentPreAdviceService lMAShipmentPreAdviceService;
	
	 /**
     * 发送预报
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/sendpreadvice")
    public String sendpreadvice(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        List<String> winitOrderNOs = new ArrayList<String>();
        String sellerManifestNo = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            sellerManifestNo = json.getString("sellerManifestNo");
            JSONArray arr = json.getJSONArray("winitOrderNOs");
            for (int i = 0; i < arr.size(); i++) {
                String j = arr.getString(i);
                winitOrderNOs.add(j);
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        
        CreateShipmentPreAdviceCommand command = new CreateShipmentPreAdviceCommand();
        command.setCtx(CommandContext.getContext());
        LMAShipmentPreAdviceVo lMAShipmentPreAdviceVo = new LMAShipmentPreAdviceVo();
        lMAShipmentPreAdviceVo.setManifestNo(sellerManifestNo);
        lMAShipmentPreAdviceVo.setOrderNos(winitOrderNOs);
        command.setlMAShipmentPreAdviceVo(lMAShipmentPreAdviceVo);
        CreatePreAdviceResult resp =   lMAShipmentPreAdviceService.addPreAdvice(command);
        
        Map<String, Object> data = new HashMap<String, Object>();
        if (resp != null) {
        	if(resp.isSuccess()){
        		 data.put("winitManifestNo",resp.getWinitManifestNo());
        		 responseMsg.setData(data);
        	}else{
        		 List<ErrorResult> errors = resp.getErrorResultList();
                 if (errors != null && errors.size() > 0) {
                     List<Map<String, Object>> errorMsgs = new ArrayList<Map<String, Object>>();
                     for (ErrorResult error : errors) {
                         Map<String, Object> map = new HashMap<String, Object>();
                         map.put("orderNo", error.getErrorOrderNo());
                         map.put("errorCode", error.getErrorCode());
                         map.put("errorMsg", error.getErrorMsg());
                         errorMsgs.add(map);
                     }
                     data.put("errorMsgs", errorMsgs);
                 }
                 responseMsg.setData(data);
                 throw new ApiException(ErrorCode.PREADVICE_CREATE_FAILURE);
        	}
        }
        return SUCCESS;
    }
	
	
    /**
     * 获取发货单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/print")
    public String print(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        String winitManifestNo = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            winitManifestNo = json.getString("winitManifestNo");
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        PrintManifestCommand printManifestCommand = new PrintManifestCommand();    
        printManifestCommand.setCtx(CommandContext.getContext());
        printManifestCommand.setManifestorderNo(winitManifestNo);
        LMAShipmentPreAdviceTaskVo  lMAShipmentPreAdviceTaskVo = lMAShipmentPreAdviceService.printManifest(printManifestCommand);
        
        if (lMAShipmentPreAdviceTaskVo == null) {
            throw new ApiException(ErrorCode.LABEL_NOT_CREATE);
        } 
        if ("PF".equals(lMAShipmentPreAdviceTaskVo.getStatus()) || "MC".equals(lMAShipmentPreAdviceTaskVo.getStatus())) {
            throw new ApiException(ErrorCode.ERP_ERROR, lMAShipmentPreAdviceTaskVo.getErrorMsg());
        }
        WinitLabelParser parser = new WinitLabelParser();
        String base64 = parser.getWinitLabelByURL(lMAShipmentPreAdviceTaskVo.getUrl());

        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("manifest", base64);
        String url = lMAShipmentPreAdviceTaskVo.getUrl();
        if (StringUtils.isNotBlank(url)) {
            String formatType = url.substring(url.lastIndexOf(".") + 1, url.length());
            if (StringUtils.isNotBlank(formatType)) {
                dataMap.put("formatType", formatType.toLowerCase());
            }
        }

        List<Map<String, Object>> labelList = new ArrayList<Map<String, Object>>();
        labelList.add(dataMap);
        responseMsg.setData(dataMap);
        return SUCCESS;
    }
    
}
